package cn.yhbk.web.modules.manager.Controller;

import cn.yhbk.web.common.Util.MyUtil;
import cn.yhbk.web.common.api.CommonResult;
import cn.yhbk.web.common.exception.ApiException;
import cn.yhbk.web.modules.manager.Pojo.Entity.BursaryRecord;
import cn.yhbk.web.modules.manager.Pojo.Entity.TbApply;
import cn.yhbk.web.modules.manager.Pojo.VO.BursaryRecord.BursaryRecordExcel;
import cn.yhbk.web.modules.manager.Pojo.VO.BursaryRecord.BursaryRecordParam;
import cn.yhbk.web.modules.manager.Pojo.VO.BursaryRecord.BursaryRecordSubmitVo;
import cn.yhbk.web.modules.manager.Pojo.VO.BursaryRecord.BursaryRecordVo;
import cn.yhbk.web.modules.manager.Service.IBursaryRecordService;
import cn.yhbk.web.modules.manager.Service.ITbApplyService;
import cn.yhbk.web.modules.manager.Service.ITbStudentService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 有何不可
 * @since 2024-02-21
 */
@RestController
@Api(tags = "奖学金名单操作接口")
@RequestMapping("/manager/bursaryRecord")
public class BursaryRecordController {

    @Autowired
    private IBursaryRecordService bursaryRecordService;

    @Autowired
    private ITbStudentService studentService;

    @PostMapping("/")
    @ApiOperation("确定该奖学金名单")
    public CommonResult setBursaryRecord(@RequestBody @Valid BursaryRecordVo set){

        //判断是否有重复确定
        boolean check = bursaryRecordService.checkHasSet(set.getResultId(),set.getBursaryId());
        if(!check)return CommonResult.failed("不能重复确认");

        boolean success = bursaryRecordService.setRecord(set.getBursaryId(),set.getSize(),set.getResultId());
        if(success)return CommonResult.success("添加成功!");

        return CommonResult.failed("添加失败!");
    }

    @ApiOperation("获取奖学金获得者名单")
    @PostMapping("/getRecord")
    public CommonResult getBursaryRecord(@RequestBody @Valid BursaryRecordParam param){
        List<BursaryRecord> resList = bursaryRecordService.getBursaryRecord(param.getResultId(),param.getBursaryId());

        return CommonResult.success("获取成功!",resList);
    }

    @ApiOperation("撤销奖学金获得者名单")
    @DeleteMapping("/")
    public CommonResult delBursaryRecord(@RequestBody @Valid BursaryRecordParam param){
        boolean success = bursaryRecordService.delBursaryRecord(param.getResultId(),param.getBursaryId());
        if(success)return CommonResult.success("撤销成功!");

        return CommonResult.failed("撤销失败!");
    }

    @ApiOperation("确定校级奖学金获得者名单")
    @PostMapping("/xiao")
    public CommonResult setBursaryRecordXiaoji(@Valid @RequestBody BursaryRecordSubmitVo req){
        Long resultId = req.getResultId();
        Integer one = req.getOne();
        Integer two = req.getTwo();
        Integer three = req.getThree();
        boolean success = bursaryRecordService.setRecord(resultId,one,two,three);
        if(success)return CommonResult.success("添加成功!");

        return CommonResult.failed("添加失败!");
    }

    @ApiOperation("导出公示结果")
    @GetMapping("/download")
    public void downloadFailedUsingJson(HttpServletResponse response,String year) throws IOException {

        boolean flag=true;
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {

            //校验年份格式
            if(!MyUtil.checkYear(year)){
                flag=false;
                throw new Exception();
            }

            List<BursaryRecordExcel> resList = bursaryRecordService.getBursaryRecordByYear(year);


            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("奖学金公示表"+year, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), BursaryRecordExcel.class).autoCloseStream(Boolean.FALSE).sheet("数据")
                    .doWrite(resList);
        } catch(Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            String message = "下载失败!";
            if(!flag)message="年份格式错误";
            response.getWriter().println(JSON.toJSONString(CommonResult.failed(message)));
        }
    }


}
